package com.liber.sun.thread;

import com.liber.sun.support.RefactorNode;
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.util.List;

/**
 * Created by sunlingzhi on 2018/3/8.
 */
//要处理的节点定义，以及对应节点应该进行的操作(runNode)
public class AdvanceHandle {
    private List<RefactorNode> nodeList;
    private String username;
    private String rootPath;

    public AdvanceHandle(List<RefactorNode> nodeList,String username,String rootPath) {
        this.nodeList = nodeList;
        this.username=username;
        this.rootPath=rootPath;
    }

    public synchronized RefactorNode runNode(int index) throws InterruptedException, ParserConfigurationException, SAXException, IOException {
        if (index < 0 || index >= this.nodeList.size()) {
            return null;
        }
        if(checkError()){//节点List中有出错的节点或者,不做任何操作，返回该节点
            return this.nodeList.get(index);
        }
        //该节点的数据未准备就绪，等待进行休眠
        while (!this.nodeList.get(index).CheckData()) {
            System.out.println(this.nodeList.get(index).getMethod() + " is waiting...");
            wait();
        }
        //计算在此进行
        if(this.nodeList.get(index).compute(this.rootPath,this.username).getFlag()&&this.nodeList.get(index).CheckData()){
            //运算成功并且所有的输出数据均存在
            System.out.println(this.nodeList.get(index).getMethod() + " is completed...");
            this.nodeList.get(index).setIsFinished(1);
        }else{
            System.out.println(this.nodeList.get(index).getMethod() + " is error...");
            this.nodeList.get(index).setIsFinished(-1);
        }
        notifyAll();
        return this.nodeList.get(index);
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getRootPath() {
        return rootPath;
    }

    public void setRootPath(String rootPath) {
        this.rootPath = rootPath;
    }

    public boolean checkError(){
        for (RefactorNode refactorNode : this.nodeList) {
            if(refactorNode.getIsFinished()==-1||refactorNode.getIsFinished()==2){
                return true;
            }
        }
        return false;
    }
}
